from fontTools.ttLib import TTFont
from fontTools.pens.freetypePen import FreeTypePen
import matplotlib.pyplot as plt
import os
import ddddocr
from PIL import Image

font_path = '11-12.woff'
output_dir = 'fontImg'

def font_split_single_img():
    # 解析字体文件
    font = TTFont('11-12.woff')  # woff2文件
    cmap = font.getBestCmap()
    # font.saveXML('font.xml')  # 保存存为xml
    index = 1
    for n, v in cmap.items():
        d = v
        glyph = font.getGlyphSet()[d]  # 通过字形名称选择某一字形对象
        pen = FreeTypePen(None)  # 实例化Pen子类
        glyph.draw(pen)  # “画”出字形轮廓
        # pen.show()    # 显示
        b = pen.array()
        print(index, '/', len(cmap), '~~~', glyph)
        plt.figure()  # 调整画布大小以适应新的显示范围
        plt.imshow(b)  # 使用灰度图显示
        plt.axis('off')  # 禁用坐标轴
        os.makedirs('imgs', exist_ok=True)
        plt.savefig(f'./imgs/{d}.jpg', bbox_inches='tight')
        # plt.show()    # 显示
        plt.clf()
        plt.cla()
        plt.close()
        index += 1
# 用 ddddocr 识别图片文字,保存至 imgs_copy_word 文件夹
def ocrWords():
    ocr = ddddocr.DdddOcr(beta=False, show_ad=False)  # 识别
    word_map = {}
    for parent, dirnames, filenames in os.walk('imgs'):  # 遍历每一张图片
        for filename in filenames:
            k = filename.split('.')[0]
            currentPath = os.path.join(parent, filename)
            with open(currentPath, 'rb') as f:
                image = f.read()
            res = ocr.classification(image)
            if len(res) == 0:
                res = '未找到'
            if len(res) > 1:
                res = res[0]
            print(k, 'res:', res)
            os.makedirs('imgs_copy_word', exist_ok=True)
            d = f'{k}__{res}.jpg'
            img = Image.open(currentPath)
            img.save('imgs_copy_word/%s' % d)
            word_map[k] = res

ocrWords()